//
//  DFAFilter.swift
//  DFAFilterDemo
//
//  Created by 张福杰 on 2019/10/23.
//  Copyright © 2019 张福杰. All rights reserved.
//

import UIKit

class DFAFilter: NSObject {
    lazy var keyword_chains: NSMutableDictionary = {
        let dict = NSMutableDictionary()
        return dict
    }()
    
    lazy var delimit: String = "\\x00";
    
    /// 读取敏感词
    func parseSensitiveWords() -> Void {
        let path = Bundle.main.path(forResource: "sensitive_words", ofType: "txt");
        let url = URL(fileURLWithPath: path!)
        do {
            let data = try Data(contentsOf: url)
            let content: String = String(data: data, encoding: String.Encoding.utf8)!
            let keyWordList = content.components(separatedBy: ",")
            for keyword in keyWordList {
                addSensitiveWords(keyword)
            }
            
        } catch let error as Error? {
            print(error?.localizedDescription as Any)
        }
    }
    
    /// 添加敏感词到敏感词树
    func addSensitiveWords(_ keyword: String) -> Void {
        let keyword: String = keyword.lowercased().trimmingCharacters(in: .whitespacesAndNewlines)
        var node = self.keyword_chains
        if keyword.count <= 0{
            return
        }
        
        for index in 0...keyword.count - 1 {
            let index0 = keyword.index(keyword.startIndex, offsetBy: index)
            let index1 = keyword.index(keyword.startIndex, offsetBy: index + 1)
            let word = keyword[index0..<index1]
            if node[word] == nil{
                node[word] = NSMutableDictionary()
            }
            node = node[word] as! NSMutableDictionary
        }
        node[self.delimit] = 0
    }
    
    /// 开始过滤敏感词
    func filterSensitiveWords(_ message: String, replaceKey: String) -> String {
        let replaceKey = replaceKey.count > 0 ? replaceKey : "*"
        let message = message.lowercased()
        let retArray: NSMutableArray = NSMutableArray()
        var start = 0
        while start < message.count {
            var level: NSMutableDictionary = self.keyword_chains.mutableCopy() as! NSMutableDictionary
            var step_ins = 0
            let message_chars = getChar(message, startIndex: start, endIndex: message.count)
            for index in 0...message_chars.count - 1 {
                let chars_i = getChar(message_chars, startIndex: index, endIndex: index + 1)
                if level[chars_i] != nil{
                    step_ins += 1
                    let level_char_dict: NSDictionary = level[chars_i] as! NSDictionary
                    if level_char_dict[self.delimit] == nil{
                        level = level_char_dict.mutableCopy() as! NSMutableDictionary
                    }else{
                        var ret_str = ""
                        for _ in 0...step_ins - 1 {
                            ret_str += replaceKey
                        }
                        retArray.add(ret_str)
                        start += (step_ins - 1)
                        break
                    }
                }else{
                    let word = getChar(message, startIndex: start, endIndex: start + 1)
                    retArray.add(word)
                    break
                }
            }
            start += 1
        }

        return retArray.componentsJoined(by: "")
    }
    
    func getChar(_ message: String, startIndex: NSInteger, endIndex: NSInteger) -> String {
        let index0 = message.index(message.startIndex, offsetBy: startIndex)
        let index1 = message.index(message.startIndex, offsetBy: endIndex)
        let word = message[index0..<index1]
        return String(word)
    }

}
